import { useHistory, useLocation } from 'react-router-dom'
import { NavBar, InfiniteScroll } from 'antd-mobile'
import ArticleItem from '@/pages/Home/components/ArticleItem'

import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { useRef } from 'react'
import { getSearchResults } from '@/store/actions/search'
import { RootState } from '@/types/store'

const Result = () => {
  const history = useHistory()
  const location = useLocation()
  const params = new URLSearchParams(location.search)
  const key = params.get('key') || ''
  const dispatch = useDispatch()
  const { searchResult } = useSelector((state: RootState) => state.search)
  const { results = [], page, per_page, total_count } = searchResult

  let hasMore = true
  const pageRef = useRef(1)
  if (total_count !== undefined && results.length < total_count) {
    hasMore = false
  }
  // useEffect(() => {
  //   dispatch(getSearchResults(key))
  // }, [dispatch, key])

  const loadMore = async () => {
    dispatch(getSearchResults(key, pageRef.current))
    pageRef.current++
  }
  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {results.map((item) => {
          return (
            <div className="article-item" key={item.art_id}>
              <ArticleItem article={item}></ArticleItem>
            </div>
          )
        })}

        <InfiniteScroll hasMore={hasMore} loadMore={loadMore}></InfiniteScroll>
      </div>
    </div>
  )
}

export default Result
